package com.amithkoujalgi.myapp.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import com.amithkoujalgi.myapp.domain.GoogleAccessToken;
import com.google.gson.Gson;

public class HTTPUtil {

	public HTTPUtil() {
	}

	List<NameValuePair> params = new ArrayList<NameValuePair>();
	Map<String, String> mapn;
	DefaultHttpClient httpClient;
	HttpPost httpPost;

	public GoogleAccessToken getGoogleToken(String address, String authorizationCode,
			String clientId, String clientSecret, String redirectUri,
			String grantType) {
		InputStream is = null;
		String json = "";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		DefaultHttpClient httpClient;
		HttpPost httpPost;
		try {
			httpClient = new DefaultHttpClient();
			httpPost = new HttpPost(address);
			params.add(new BasicNameValuePair("code", authorizationCode));
			params.add(new BasicNameValuePair("client_id", clientId));
			params.add(new BasicNameValuePair("client_secret", clientSecret));
			params.add(new BasicNameValuePair("redirect_uri", redirectUri));
			params.add(new BasicNameValuePair("grant_type", grantType));
			httpPost.setHeader("Content-Type",
					"application/x-www-form-urlencoded");
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("HTTPClient", e.getMessage());
		}
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			Log.e("JSONStr", json);
		} catch (Exception e) {
			e.getMessage();
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}
		GoogleAccessToken t = null;
		try {
			t = new Gson().fromJson(json, GoogleAccessToken.class);
		} catch (Exception e) {
			Log.e("GSON Parser", "Error parsing data " + e.toString());
		}
		return t;
	}
}